package ginx

import (
	"net/http"

	"gitee.com/iece/common/rest"
	"github.com/gin-gonic/gin"
)

type DataHandlerFunc func(c *gin.Context) (data any, err error)

// 处理返回数据
func DataHandler(fn DataHandlerFunc) gin.HandlerFunc {
	return func(c *gin.Context) {
		data, err := fn(c)
		jsonResp := rest.JsonRespData(data, err)
		httpCode := jsonResp.Code
		if err != nil {
			if httpCode >= 1000 { // 业务自定义错误码
				httpCode = http.StatusOK
			} else if http.StatusText(httpCode) == "" { // 通用http响应码
				httpCode = http.StatusInternalServerError
			}
		} else {
			httpCode = http.StatusOK
		}
		c.JSON(httpCode, jsonResp)
	}
}
